﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using brjostagjof.Models;
using System.Diagnostics;
using System.Web.Security;
using System.IO;

namespace brjostagjof.Controllers
{
    public class MySiteController : Controller
    {
        DataRepository rep = new DataRepository();

        [HttpGet]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult Index()
        {

            MySiteContainer ourMySite = new MySiteContainer();
            ourMySite = rep.GetMySite((rep.GetUserByName(User.Identity.Name)).ID);
            if (ourMySite.pic == null)
            {
                if (ourMySite.theUser.gender == true)
                {
                    ourMySite.pic = rep.GetPicByPictureID(9); // Default Picture if you have no profile picture selected
                }
                else
                {
                    ourMySite.pic = rep.GetPicByPictureID(10);
                }
            }
            return View(ourMySite);
        }

        
        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult AddChild()
        {
            FormCollection formData = new FormCollection(Request.Form);
            Children model = new Children();
            model.age = int.Parse(formData["newchild.age"]);
            model.description = formData["newchild.description"];
            model.name = formData["newchild.name"];
            model.publicUserID = (rep.GetUserByName(User.Identity.Name)).ID;
            if (formData != null)
            {
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                        Debug.WriteLine(file.FileName);
                        Debug.WriteLine(Path.GetFileName(file.FileName));
                        
                        string filePath = Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), Path.GetFileName(file.FileName));
                        string filePath2 = Path.Combine("Uploads/", Path.GetFileName(file.FileName));
                        bool isfilevalid = rep.IsPicNameValid(filePath2);
                        if (isfilevalid)
                        {
                            file.SaveAs(filePath);
                            Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                            rep.CreateChildWithPhoto(pic, model);
                        }
                        else
                        {

                            Random rand = new Random();
                            int theNumber = rand.Next(99999999);
                            filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), theNumber.ToString()
                               + Path.GetFileName(file.FileName));
                            FileInfo fi = new FileInfo(filePath);
                            file.SaveAs(filePath);
                            filePath2 = Path.Combine("Uploads/", theNumber.ToString() + Path.GetFileName(file.FileName));
                            isfilevalid = rep.IsPicNameValid(filePath2);
                            if (isfilevalid)
                            {
                                file.SaveAs(filePath);
                                Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                                rep.CreateChildWithPhoto(pic, model);
                            }
                        }
                    }
                    else
                    {
                        rep.CreateChild(model);
                    }
                }

                return RedirectToAction("Index");
            }

            else
            {
                return View("Not Found");
            }
        }
        
        [HttpGet]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult EditChild(int? ID)
        {
            if (ID != null)
            {
                var model = rep.GetChildByID(ID.Value);

                if (model == null)
                {
                    return View("Not found");
                }
                else
                {
                    return View(model);
                }
            }
            else
            {
                return View("Not found");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult EditChild()
        {
            FormCollection formData = new FormCollection(Request.Form);
            Children model = new Children();
            model.age = int.Parse(formData["age"]);
            model.description = formData["description"];
            model.name = formData["name"];
            model.publicUserID= (rep.GetUserByName(User.Identity.Name)).ID;
            model.ID = int.Parse(formData["ID"]);
            if (formData != null)
            {
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                    string filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), Path.GetFileName(file.FileName));
                        string filePath2 = Path.Combine("Uploads/", Path.GetFileName(file.FileName));
                        bool isfilevalid = rep.IsPicNameValid(filePath2);
                        if (isfilevalid)
                        {
                            file.SaveAs(filePath);
                            Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                            rep.UpdateChildWithPhoto(pic, model);
                        }
                        else
                        {

                            Random rand = new Random();
                            int theNumber = rand.Next(99999999);
                            filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), theNumber.ToString()
                               + Path.GetFileName(file.FileName));
                            FileInfo fi = new FileInfo(filePath);
                            file.SaveAs(filePath);
                            filePath2 = Path.Combine("Uploads/", theNumber.ToString() + Path.GetFileName(file.FileName));
                            isfilevalid = rep.IsPicNameValid(filePath2);
                            if (isfilevalid)
                            {
                                file.SaveAs(filePath);
                                Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                                rep.UpdateChildWithPhoto(pic, model);
                            }
                        }
                    }
                    else
                    {
                        rep.UpdateChild(model);
                    }
                }

                return RedirectToAction("Index");
            }

            else
            {
                return View("Not Found");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult RemoveChild(int? ID)
        {
            var result = rep.GetChildByID(ID.Value);
            rep.DeleteChild(result);
            return View("Index");
        }

        [HttpGet]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult AddTimeline(int? ID)
        {
            if (ID.HasValue)
            {
                TimeLineEntry model = new TimeLineEntry();
                model.childID = ID.Value;
                model.date = DateTime.Now;
                return View(model);
            }
            else
            {
                return View("Not Found");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult AddTimeline()
        {
            FormCollection formData = new FormCollection(Request.Form);
            TimeLineEntry model = new TimeLineEntry();
            model.childID=int.Parse(formData["childID"]);
            model.date=DateTime.Parse(formData["date"]);
            model.description=formData["description"];
            if (formData != null)
            {
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                    string filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads")
                                , Path.GetFileName(file.FileName));
                        string filePath2 = Path.Combine("Uploads/", Path.GetFileName(file.FileName));
                        bool isfilevalid = rep.IsPicNameValid(filePath2);
                        if (isfilevalid)
                        {
                            file.SaveAs(filePath);
                            Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                            rep.SavePicAndTimelineEntryToDB(pic, model);
                        }
                        else
                        {

                            Random rand = new Random();
                            int theNumber = rand.Next(99999999);
                            filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), theNumber.ToString()
                               + Path.GetFileName(file.FileName));
                            FileInfo fi = new FileInfo(filePath);
                            file.SaveAs(filePath);
                            filePath2 = Path.Combine("Uploads/", theNumber.ToString() + Path.GetFileName(file.FileName));
                            isfilevalid = rep.IsPicNameValid(filePath2);
                            if (isfilevalid)
                            {
                                file.SaveAs(filePath);
                                Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                                rep.SavePicAndTimelineEntryToDB(pic, model);
                            }
                        }
                    }
                    else
                    {
                        rep.SaveTimelineEntryToDB(model);
                    }
                }

                return RedirectToAction("Index");
            }

            else
            {
                return View("Not Found");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult AddUserToContacts(ArticleBaseCollection result)
        {
            Contact con = new Contact();
            int ID = (rep.GetUserByName(User.Identity.Name)).ID;
            if (result.informationBaseID == ID)
            {
                return Json("You cannot befriend yourself", JsonRequestBehavior.AllowGet);
            }

            con = rep.GetContacts(ID, result.informationBaseID);
            if (con == null)
            {
                Contact con2 = new Contact();
                con2.userID1 = ID;
                con2.userID2 = result.informationBaseID;
                rep.SaveContact(con2);
                return Json("", JsonRequestBehavior.AllowGet);
            }
            return Json("You have already added this User", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult AddGrein(ArticleBaseCollection result)
        {
            ArticleBaseCollection ArtyColl = new ArticleBaseCollection();
            int ID = (rep.GetUserByName(User.Identity.Name)).ID;
            ArtyColl = rep.GetCollectionByUserAndID(ID, result.informationBaseID);

            if (ArtyColl == null)
            {
                ArticleBaseCollection ArtyColl2 = new ArticleBaseCollection();
                ArtyColl2.userID = ID;
                ArtyColl2.informationBaseID = result.informationBaseID;
                rep.AddArticleBaseCollection(ArtyColl2);
                return Json("", JsonRequestBehavior.AllowGet);
            }
            return Json("Þú hefur þegar bætt þessari grein í safnið þitt", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult DeleteGrein(ArticleBaseCollection result)
        {

            ArticleBaseCollection ArtyColl = new ArticleBaseCollection();

            ArtyColl = rep.GetCollectionByUserAndID(result.userID, result.informationBaseID);

            if (ArtyColl != null)
            {
                rep.DeleteArticleBaseCollection(ArtyColl);
                return Json("", JsonRequestBehavior.AllowGet);
            }
            return Json("", JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult DeleteUserContact(Contact result)
        {
            if (result != null)
            {
                rep.DeleteContact(result.userID1, result.userID2);
            }
            return Json("", JsonRequestBehavior.AllowGet);

        }


        [HttpGet]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult EditMyProfile(int? id)
        {
            if (id != null)
            {
                int num = Convert.ToInt32(id);
                if (rep.GetUserByID(num) != rep.GetUserByName(User.Identity.Name))
                {
                    return View("Not Found");
                }
                var model = rep.GetUserByID(num);

                if (model == null)
                {
                    return View("Not Found");
                }
                else
                {
                    return View(model);
                }
            }
            else
            {
                return View("Not Found");
            }
        }

        [HttpPost]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        [ValidateInput(false)]
        public ActionResult EditMyProfile()
        {
            //Temp-stefan vantar kannski sma validation a Inbput!
            FormCollection formData = new FormCollection(Request.Form);
            User model = new User();
            model.ID = int.Parse(formData["ID"]);
            model.age = int.Parse(formData["age"]);
            model.description = formData["description"];
            model.zipCode = int.Parse(formData["zipCode"]);
            model.email = formData["email"];
            model.name = formData["name"];
            model.address = formData["address"];

            if (formData != null)
            {
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                    string filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads")
                                , Path.GetFileName(file.FileName));
                        string filePath2 = Path.Combine("Uploads/", Path.GetFileName(file.FileName));
                        bool isfilevalid = rep.IsPicNameValid(filePath2);
                        if (isfilevalid)
                        {
                            file.SaveAs(filePath);
                            Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                            rep.UpdateMyProfileAndPicture(pic, model);
                        }
                        else
                        {

                            Random rand = new Random();
                            int theNumber = rand.Next(99999999);
                            filePath=Path.Combine(HttpContext.Server.MapPath("~/Images/Uploads"), theNumber.ToString()
                               + Path.GetFileName(file.FileName));
                            FileInfo fi = new FileInfo(filePath);
                            file.SaveAs(filePath);
                            filePath2 = Path.Combine("Uploads/", theNumber.ToString() + Path.GetFileName(file.FileName));
                            isfilevalid = rep.IsPicNameValid(filePath2);
                            if (isfilevalid)
                            {
                                file.SaveAs(filePath);
                                Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                                rep.UpdateMyProfileAndPicture(pic, model);
                            }
                        }
                    }
                    else
                    {
                        rep.UpdateMyProfile(model);
                    }
                }

                return RedirectToAction("Index");
            }

            else
            {
                return View("Not Found");
            }
        }


        [HttpGet]
        [Authorize(Roles = "Administrators")]
        public ActionResult AddSurvey()
        {
            return View(new SurveyContainer());
        }

        [HttpPost]
        [Authorize(Roles = "Administrators")]
        public ActionResult AddSurvey(FormCollection formData)
        {
            if (!string.IsNullOrEmpty(formData["question"]) || !string.IsNullOrEmpty(formData["option1"]) || !string.IsNullOrEmpty(formData["option2"]))
            {
                int i = 1;
                List<Choice> choices = new List<Choice>();
                for (; ; )
                {
                    Choice choice = new Choice { choice1 = formData["option" + i] };
                    if (string.IsNullOrEmpty(choice.choice1))
                    {
                        break;
                    }
                    choice.count = 0;
                    choices.Add(choice);
                    i++;
                }
                IEnumerable<Choice> resultChoices = choices;
                Survey survey = new Survey { creationDate = DateTime.Now, question = formData["question"] };
                SurveyContainer surveyResult = new SurveyContainer { choices = resultChoices, survey = survey };
                rep.CreateSurvey(surveyResult);
                return RedirectToAction("Index");
            }
            return View(new SurveyContainer());
        }

        [HttpGet]
        [Authorize(Roles = "Specialists, Administrators, PublicUser")]
        public ActionResult ViewUserByID(int ID)
        {
            User result = new User();
            result = rep.GetUserByID(ID);
            if (result.profilePictureID.HasValue)
            {
                ViewData["photo"] = (rep.GetPicByPictureID(result.profilePictureID.Value)).url;
            }
            else
            {
                if (result.gender == true)
                {
                    ViewData["photo"] = (rep.GetPicByPictureID(9)).url;
                }
                else
                {
                    ViewData["photo"] = (rep.GetPicByPictureID(10)).url;
                }
            }
            return View(result);
        }

        #region upload

        [HttpPost]
        public ActionResult Upload()
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("../Images/Uploads")
                            , Path.GetFileName(file.FileName));
                    string filePath2 = Path.Combine("/Uploads/", Path.GetFileName(file.FileName));
                    bool isfilevalid = rep.IsPicNameValid(filePath2);
                    if (isfilevalid)
                    {
                        file.SaveAs(filePath);
                        Picture pic = new Picture { url = filePath2, userID = (rep.GetUserByName(User.Identity.Name)).ID };
                        rep.SavePicToDB(pic);
                    }
                    else
                    {
                                                                    // VILLUBOÐ UM AÐ NAFN ER NU ÞEGAR TIL
                    }
                }
                
            }
            return RedirectToAction("Index");
        }
        #endregion

        
    }
}
